using B.S.XZYData.Api.Wrter.Application.Command.Approval;
using B.S.XZYData.Domain.ZSH;
using B.S.XZYData.ErrorCode;
using B.S.XZYData.Infrastructure.Interface;
using MediatR;
using Microsoft.Extensions.Logging;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace B.S.XZYData.Api.Wrter.Application.Handler.Approval
{
    /// <summary>
    /// 批量审批处理器
    /// </summary>
    public class BatchProcessApprovalHandler : IRequestHandler<BatchProcessApprovalCommand, ApiResult<BatchProcessResult>>
    {
        private readonly IBaseRepository<WorkflowInstanceModel> _workflowInstanceRepo;
        private readonly IBaseRepository<AuditModel> _auditRepo;
        private readonly ILogger<BatchProcessApprovalHandler> _logger;

        public BatchProcessApprovalHandler(
            IBaseRepository<WorkflowInstanceModel> workflowInstanceRepo,
            IBaseRepository<AuditModel> auditRepo,
            ILogger<BatchProcessApprovalHandler> logger)
        {
            _workflowInstanceRepo = workflowInstanceRepo;
            _auditRepo = auditRepo;
            _logger = logger;
        }

        public async Task<ApiResult<BatchProcessResult>> Handle(BatchProcessApprovalCommand request, CancellationToken cancellationToken)
        {
            var res = new ApiResult<BatchProcessResult>();
            var result = new BatchProcessResult();

            try
            {
                _logger.LogInformation("开始批量审批，共 {Count} 个流程实例", request.WorkflowInstanceIds.Length);

                // 查询所有要处理的流程实例
                var workflowInstances = await _workflowInstanceRepo.GetAll()
                    .Where(x => request.WorkflowInstanceIds.Contains(x.Id))
                    .ToListAsync();

                if (workflowInstances.Count == 0)
                {
                    res.Code = ApiEnum.Fail;
                    res.Msg = "未找到要处理的流程实例";
                    return res;
                }

                // 逐个处理每个流程实例
                foreach (var workflowInstanceId in request.WorkflowInstanceIds)
                {
                    try
                    {
                        var workflowInstance = workflowInstances.FirstOrDefault(x => x.Id == workflowInstanceId);
                        if (workflowInstance == null)
                        {
                            result.FailCount++;
                            result.Errors.Add(new BatchProcessError
                            {
                                WorkflowInstanceId = workflowInstanceId,
                                ErrorMessage = "流程实例不存在"
                            });
                            continue;
                        }

                        // 验证状态是否允许审批
                        if (workflowInstance.Status == "通过" || workflowInstance.Status == "驳回")
                        {
                            result.FailCount++;
                            result.Errors.Add(new BatchProcessError
                            {
                                WorkflowInstanceId = workflowInstanceId,
                                ErrorMessage = "该流程已完成，不能重复审批"
                            });
                            continue;
                        }

                        // 验证审批权限（可选：检查是否为指定审批人）
                        if (!string.IsNullOrEmpty(workflowInstance.AuditUserId) && 
                            workflowInstance.AuditUserId != request.AuditUserId.ToString())
                        {
                            result.FailCount++;
                            result.Errors.Add(new BatchProcessError
                            {
                                WorkflowInstanceId = workflowInstanceId,
                                ErrorMessage = "您没有权限审批此流程"
                            });
                            continue;
                        }

                        // 开始事务处理单个流程
                        await _workflowInstanceRepo.BeginTranAsync();

                        try
                        {
                            // 更新流程实例状态
                            var newStatus = request.OperationType == "通过" ? "通过" : "驳回";
                            workflowInstance.Status = newStatus;
                            workflowInstance.AuditUserName = request.AuditUserName;
                            workflowInstance.AuditUserId = request.AuditUserId.ToString();
                            workflowInstance.StepName = request.StepName ?? "审批完成";
                            workflowInstance.ModifyTime = DateTime.Now;
                            
                            if (newStatus == "通过" || newStatus == "驳回")
                            {
                                workflowInstance.CompletedTime = DateTime.Now;
                            }

                            await _workflowInstanceRepo.UpdateAsync(workflowInstance);

                            // 记录审批历史
                            var auditRecord = new AuditModel
                            {
                                WorkflowId = workflowInstanceId.ToString(),
                                StepId = "STEP_" + workflowInstanceId,
                                StepName = request.StepName ?? "审批",
                                ExecutePointerId = "EP_" + workflowInstanceId,
                                AuditUserName = request.AuditUserName,
                                AuditUserId = request.AuditUserId,
                                OperationType = request.OperationType,
                                Remark = request.Comment,
                                Status = request.OperationType == "通过",
                                CreateTime = DateTime.Now,
                                CreatorId = (int)request.AuditUserId
                            };

                            await _auditRepo.CreateAsync(auditRecord);

                            // 提交事务
                            await _workflowInstanceRepo.CommitTranAsync();

                            result.SuccessCount++;
                            _logger.LogDebug("批量审批成功处理流程实例ID: {WorkflowInstanceId}", workflowInstanceId);
                        }
                        catch (Exception ex)
                        {
                            // 回滚事务
                            await _workflowInstanceRepo.RollbackTranAsync();
                            
                            result.FailCount++;
                            result.Errors.Add(new BatchProcessError
                            {
                                WorkflowInstanceId = workflowInstanceId,
                                ErrorMessage = "处理失败：" + ex.Message
                            });
                            
                            _logger.LogError(ex, "批量审批处理失败，流程实例ID: {WorkflowInstanceId}", workflowInstanceId);
                        }
                    }
                    catch (Exception ex)
                    {
                        result.FailCount++;
                        result.Errors.Add(new BatchProcessError
                        {
                            WorkflowInstanceId = workflowInstanceId,
                            ErrorMessage = "处理异常：" + ex.Message
                        });
                        
                        _logger.LogError(ex, "批量审批处理异常，流程实例ID: {WorkflowInstanceId}", workflowInstanceId);
                    }
                }

                res.Code = ApiEnum.Success;
                res.Msg = $"批量审批完成，成功 {result.SuccessCount} 个，失败 {result.FailCount} 个";
                res.Data = result;

                _logger.LogInformation("批量审批完成，成功: {SuccessCount}, 失败: {FailCount}", 
                    result.SuccessCount, result.FailCount);

                return res;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "批量审批处理异常");
                res.Code = ApiEnum.Fail;
                res.Msg = "批量审批处理失败：" + ex.Message;
                res.Data = result;
                return res;
            }
        }
    }
} 